{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "73bd968b-d970-4a05-94ef-4e7abf990827",
   "metadata": {},
   "source": [
    "Chapter 04\n",
    "\n",
    "# 求根\n",
    "Book_3《数学要素》 | 鸢尾花书：从加减乘除到机器学习 (第二版)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31cdebe4-0b0d-42dc-a9ea-f4b908459cea",
   "metadata": {},
   "source": [
    "该代码利用`sympy`和`numpy`库分别求解多项式方程$$-x^3 + x = 0$$的根。首先，`sympy`库使用符号运算求解此方程。将方程因式分解为$$x(x^2 - 1) = 0$$，得到三个根：\n",
    "\n",
    "$$\n",
    "x = 0, \\quad x = 1, \\quad x = -1\n",
    "$$\n",
    "\n",
    "接着，代码使用`numpy`中的`roots`函数来计算方程的数值解。通过提供系数列表`[-1, 0, 1, 0]`（对应于方程的项$-x^3 + x$），`numpy`计算出该方程的根，得到相同的结果。\n",
    "\n",
    "这种方法的优势在于同时展示了符号解与数值解的不同计算方式：`sympy`适合精确解法，而`numpy`则高效处理数值计算。两者结合可有效应对多项式方程的多种求解需求。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8d7941d-f4f5-40bb-a686-1e1caed40945",
   "metadata": {},
   "source": [
    "## 使用 sympy 求解方程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "706d62df-e328-4a98-8927-ef588361c735",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[-1, 0, 1]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sympy.solvers import solve\n",
    "from sympy import Symbol\n",
    "\n",
    "x = Symbol('x')  # 定义符号x\n",
    "\n",
    "roots = solve(-x**3 + x, x)  # 求解方程 -x^3 + x = 0\n",
    "roots  # 输出方程的根"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7249b8d-18bf-443a-927c-61ae269f9179",
   "metadata": {},
   "source": [
    "## 使用 numpy 求解方程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ee053c88-bb21-4e5d-8c39-d21a738588ee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1., -1.,  0.])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "coeff = [-1, 0, 1, 0]  # 定义方程的系数\n",
    "\n",
    "roots_V2 = np.roots(coeff)  # 使用 numpy 求解多项式的根\n",
    "roots_V2  # 输出方程的根"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85a80909-2aac-49ed-bb7a-f8cc6b80ee7d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecd322f4-f919-4be2-adc3-69d28ef25e69",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
